﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Diagnostics;
using System.Linq;
using LoveMusic.Helpers;

namespace Dal
{
    public class MusicDataAccess : IMusicDataAccess
    {
        public BotStatus GetBotStatus()
        {
            using (ModelDataContext db = new ModelDataContext())
            {
                db.ObjectTrackingEnabled = false; // retrieving data read only
                return db.BotStatus.First();
            }
        }

        public void UpdateBotStatus(BotStatus botStatus)
        {
            Debug.Assert(botStatus != null);
            using (ModelDataContext db = new ModelDataContext())
            {
                db.BotStatus.Attach(botStatus);
                db.SubmitChanges();
            }

        }

        public List<Tag> GetTagStatus(List<Tag> tags)
        {
            foreach (Tag tag in tags)
            {
                var tempTag = GetTag(tag.Name);

                if (tempTag == null)
                {
                    var getTag = InsertTag(tag);
                    tag.ID = getTag.ID;
                    tag.status = 1;//New
                }
                else
                {
                    tag.status = 0;//Old
                    tag.ID = tempTag.ID;
                }
            }
            return tags;
        }

        public Tag GetTag(string tagName)
        {
            try
            {
                using (ModelDataContext db = new ModelDataContext())
                {
                    db.DeferredLoadingEnabled = false;
                    return db.Tags.FirstOrDefault(t => t.Name == tagName);
                }
            }
            catch (Exception e)
            {
                return null;
            }
        }

        private Tag InsertTag(Tag tag)
        {
            using (ModelDataContext db = new ModelDataContext())
            {
                db.DeferredLoadingEnabled = false;
                db.Tags.InsertOnSubmit(tag);
                db.SubmitChanges();
            }
            return GetTag(tag.Name);
        }

        public void InsertTags(List<string> tags)
        {
            using (ModelDataContext db = new ModelDataContext())
            {
                foreach (string tagyString in tags)
                {
                    db.DeferredLoadingEnabled = false;
                    var tag = db.Tags.Where(s => s.Name == tagyString).FirstOrDefault();

                    if (tag != null)
                    {
                        tag.SetAsInsertOnSubmit();
                        tag.SynchroniseWithDataContext(db, true);
                    }
                }

                db.SubmitChanges();
            }

            //foreach (Tag tagy in tags)
            //{
            //    tagy.ID = GetTag(tagy.Name).ID;
            //}

        }

        public Wrapper GetStories(int skip, int take, Wrapper wrapper)
        {
            try
            {
                List<int> listTakenIDs = wrapper.takenIDs;
                List<Story> songs;

                using (ModelDataContext db = new ModelDataContext())
                {
                    db.DeferredLoadingEnabled = false;
                    //DataLoadOptions lo = new DataLoadOptions();
                    //lo.LoadWith<Story>(c => c.StoryTags);
                    //lo.LoadWith<StoryTag>(c => c.Tag);

                    //db.LoadOptions = lo;

                    songs = db.Stories.Where(s => s.Status == 0 && !listTakenIDs.Contains(s.ID)).Take(take).ToList();

                }

                // Add only the latest id's
                wrapper.takenIDs = new List<int>();
                foreach (Story song in songs)
                {
                    wrapper.takenIDs.Add(song.ID);
                }

                wrapper.songs = songs;
            }
            catch (Exception e)
            {
                wrapper.errorDetails = e;
            }

            return wrapper;
        }

        public Wrapper UpdateStories(Wrapper wrapper)
        {
            Debug.Assert(wrapper.songs != null);
            try
            {
                using (ModelDataContext db = new ModelDataContext())
                {
                    db.DeferredLoadingEnabled = false;

                    foreach (Story story in wrapper.songs)
                    {
                        wrapper.removeIDs.Add(story.ID);

                        db.spInsertStoryTags(story.inputTags, story.ID);

                        #region Tags

                        //if (!string.IsNullOrEmpty(story.inputTags))
                        //{
                        //    var tagsArray = story.inputTags.Split(',');
                        //    var newTags = new List<Tag>();
                        //    var allTags = new List<Tag>();

                        //    for (var i = 0; i < tagsArray.Length; i++)
                        //    {
                        //        var tagName = tagsArray[i].Trim();

                        //        if (tagName.Length > 0)
                        //        {
                        //            if (tagName.Length > 64)
                        //                tagName = tagName.Substring(0, 64);
                        //            var tag = db.Tags.FirstOrDefault(t => t.Name == tagName);

                        //            if (tag == null)
                        //            {
                        //                tag = new Tag { Name = tagName };
                        //                tag.SetAsChangeTrackingRoot(EntityState.New);
                        //                tag.SetAsInsertOnSubmit();
                        //                tag.SynchroniseWithDataContext(db, true);
                        //                newTags.Add(tag);
                        //            }
                        //            else
                        //                allTags.Add(tag);
                        //        }
                        //    }



                        //    if (allTags.Count > 0)
                        //    {
                        //        var storyTags = new List<StoryTag>();

                        //        for (var i = 0; i < allTags.Count; i++)
                        //        {
                        //            var storyTag = new StoryTag { StoryID = story.ID, TagID = allTags[i].ID };
                        //            storyTag.SetAsChangeTrackingRoot(EntityState.New);
                        //            storyTag.SetAsInsertOnSubmit();
                        //            storyTag.SynchroniseWithDataContext(db, true);
                        //        }
                        //    }



                        //}

                        #endregion

                        story.SynchroniseWithDataContext(db, true);
                    }


                    db.SubmitChanges();
                }
            }
            catch (Exception e)
            {
                wrapper.errorDetails = e;
            }

            return wrapper;
        }



        public int SubmitBotBillBoard(string songName, int category, string description, string artistName)
        {
            string encodingCode = string.Empty;
            string tags = string.Empty;
            string videoID = string.Empty;
            string imageURL = string.Empty;
            string youTubeDescrption = string.Empty;
            //songTitle = WebHelper.RemoveSpecialCharacters(songTitle);
            artistName = WebHelper.RemoveSpecialCharactersExceptTire(artistName);
            Mp3FileApi mp3FileApi = new Mp3FileApi();
            List<string> lstMp3Songs = mp3FileApi.GetMp3Urls(artistName, songName);
            YouTubeApi youTube = new YouTubeApi();
            youTube.GetYouTubeVideo(songName, artistName, ref encodingCode, ref videoID, ref tags, ref youTubeDescrption);

            using (ModelDataContext db = new ModelDataContext())
            {
                if (artistName != "TI")
                    if (!db.StoryExists(songName, artistName))
                    {
                        db.SubmitStoryBot(songName, artistName, category, description, tags, lstMp3Songs , videoID, new Guid("1685CC87-BA2F-450B-BBE6-2F81A0F149A9"), youTubeDescrption);
                    }
            }

            return 0;
        }

        public List<ARTIST> GetArtists(int take, int skip)
        {
            using (ModelDataContext db = new ModelDataContext())
            {
                db.ObjectTrackingEnabled = false; // retrieving data read only
                return db.ARTISTs.Where(s => s.status != 69 && s.status != 70).Take(take).ToList();
            }
        }

        public int SubmitBotLastFM(List<Story> stories)
        {
            try
            {
                using (ModelDataContext db = new ModelDataContext())
                {
                    int artistIDZ = 0;
                    db.DeferredLoadingEnabled = false;

                    foreach (Story story in stories)
                    {
                        artistIDZ = story.ARTIST_IDZ;
                        story.SynchroniseWithDataContext(db, true);
                        db.Stories.InsertOnSubmit(story);
                    }

                    // Na obraboten artist mu stava status 69 sto znaci zavrseno e so nego
                    if (artistIDZ != 0)
                        db.ARTISTs.Where(s => s.ARTIST_IDZ == artistIDZ).FirstOrDefault().status = 69;

                    db.SubmitChanges();
                }

                return 0;
            }
            catch (Exception ex)
            {
                return 11111;
            }
        }

        /// <summary>
        /// If artist success 69 else songless artist status=70!
        /// </summary>
        /// <param name="artist"></param>
        public void SetArtistSongless(ARTIST artist)
        {
            using (ModelDataContext db = new ModelDataContext())
            {
                db.DeferredLoadingEnabled = false;
                db.ARTISTs.Where(s => s.ARTIST_IDZ == artist.ARTIST_IDZ).FirstOrDefault().status = 70;
                //artist.SynchroniseWithDataContext(db, true);
                db.SubmitChanges();
            }
        }
    }
}
